package es.ats.codington.Spring.Controllers;

import java.io.IOException;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import es.ats.codington.festival.domain.Event;

import es.ats.codington.festival.domain.Visitor;
import es.ats.codington.festival.services.EventSingUpService;
import es.ats.codington.festival.services.VisitorServiceImpl;

/**
 * The Class VisitorsController.
 *
 * @author 5Cs
 */
@Controller
public class VisitorsController {

	/**
	 * Login controller.
	 *
	 * @param request the request
	 * @param response the response
	 * @return the string
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	@RequestMapping(value = "/login.htm")
	public String loginController(HttpServletRequest request, HttpServletResponse response) throws IOException {		
		try {
			Visitor visitorInserted = new Visitor();
			visitorInserted.setUsername(request.getParameter("username"));
			visitorInserted.setPassword(request.getParameter("password"));
			
			VisitorServiceImpl visitorService = new VisitorServiceImpl();
			Visitor visitorFound = visitorService.login(visitorInserted);
			if(visitorFound == null){
				request.setAttribute("error", "Login incorrect.");
				return "login";
			}		
			else{
				request.getSession().setAttribute("visitor", visitorFound);
				
				if(visitorFound.isAdmin()){
					request.getSession().setAttribute("admin", 1);
					return "redirect:/eventAdmin.htm";									
				}
				else {
					request.getSession().setAttribute("admin", 0);
					return "redirect:/actArray.htm";
				}
				
			}
		} catch (Exception e) {
			request.setAttribute("error", "Login incorrect.");
			return "login";
		}
	}
	
	/**
	 * Update info controller.
	 *
	 * @param request the request
	 * @param response the response
	 * @return the string
	 * @throws Exception the exception
	 */
	@RequestMapping(value = "/updateInfo.htm")
	public String updateInfoController(HttpServletRequest request, HttpServletResponse response) throws Exception {	
        VisitorServiceImpl vis = new VisitorServiceImpl();
        Visitor visitor= (Visitor)request.getSession().getAttribute("visitor");
        int id = visitor.getVisitorId();
        try {
			visitor = vis.searchVisitorById(id);
			request.getSession().setAttribute("visitor", visitor);
		} catch (Exception e) {
			e.printStackTrace();
		}                               
        
		return "updateVisitor";
	}
	
	/**
	 * Update visitor controller.
	 *
	 * @param request the request
	 * @param response the response
	 * @return the string
	 */
	@RequestMapping(value = "/updateVisitor.htm")
	public String updateVisitorController(HttpServletRequest request, HttpServletResponse response) {
		int result=0;
		try{
			Visitor v= (Visitor)request.getSession().getAttribute("visitor");
	        int id = v.getVisitorId();
	        String pas= v.getPassword();
	        
            VisitorServiceImpl vis = new VisitorServiceImpl();
			
			
			String username = request.getParameter("username");
			String name = request.getParameter("name");
			
			String lastname = request.getParameter("lastname");
			String age = request.getParameter("age").toString().replace("/", "");
			String address = request.getParameter("address").replace("/", "");
			String phone = request.getParameter("phone");
			
            Visitor visitor = new Visitor();
            
            int a= Integer.parseInt(age);
            
            visitor.setName(name);
			visitor.setLastName(lastname);
			visitor.setAge(a);
			visitor.setAddress(address);
			visitor.setPhoneNumber(phone);
			visitor.setUsername(username);
			visitor.setVisitorId(id);
			visitor.setPassword(pas);
			if (v.isAdmin()) visitor.setAdmin(true);
            
            result= vis.updateVisitor(visitor);  
            
    		if(result == 0){
				request.setAttribute("error", "Update Info incorrect.");
				return "updateVisitor";
			}		

			else{
				request.setAttribute("ok", "Profile update succesfully");
				/*int admin = (Integer) request.getAttribute("admin");*/
				if (v.isAdmin())  return "redirect:/eventAdmin.htm";
				else return "redirect:/actArray.htm";
			}

           
        }catch(Exception theException){
        	request.setAttribute("error", "Update Infor incorrect."+ theException.getMessage());
			return "updateVisitor";
        }
	
	}
	
	

	/**
	 * Actual arrays to send jsp.
	 *
	 * @param request the request
	 * @return the model and view
	 */
	@RequestMapping(value = "/actArray.htm")
	public ModelAndView actualArraysToSendJsp(HttpServletRequest request){
		
		 HttpSession session = request.getSession(true);
		 Visitor visitor = (Visitor) request.getSession().getAttribute("visitor");
		 int IdVisitor = visitor.getVisitorId();
		 ModelAndView model = new ModelAndView();
		 try{		
				/**
				 * Your Events
				 */
				
				/* Prueba */
				EventSingUpService ev = new EventSingUpService();				
				ArrayList<Event> event = new ArrayList<Event>();
				boolean result = ev.visitorInEvent(IdVisitor, event);
				
				/**
				 * All Events
				 */
				EventSingUpService ev2 = new EventSingUpService();					
				ArrayList<Event> event2 = new ArrayList<Event>();
				boolean result2 = ev.obtainSemiAllEvents(IdVisitor, event2);
				
				model.addObject("YourEvents", event);
				model.addObject("SemiAllEvents", event2);
				model.setViewName("listEventVisitor");
			
					
		    }catch(Exception theException){
		        System.out.println(theException); 
		   }
		return model;
					
	}
	

	/**
	 * Logout controller.
	 *
	 * @param request the request
	 * @param response the response
	 * @return the string
	 */
	@RequestMapping(value = "/logout.htm")
	public String logoutController(HttpServletRequest request, HttpServletResponse response) {
		HttpSession sesion = request.getSession(true);
		sesion.invalidate();
		return "login";
	}
	
	/**
	 * Register controller.
	 *
	 * @return the string
	 */
	@RequestMapping(value = "/createvisitor.htm")
	public String registerController() {
		return "registerVisitor";
	}


	/**
	 * Validater register controller.
	 *
	 * @param request the request
	 * @param response the response
	 * @return the string
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	@RequestMapping(value = "/register.htm")
	public String validaterRegisterController(HttpServletRequest request, HttpServletResponse response) throws IOException {
	
		boolean created = false;
		try {

			VisitorServiceImpl visitorService = new VisitorServiceImpl();
			Visitor visitor = new Visitor();
			visitor.setName(request.getParameter("name"));
			visitor.setLastName(request.getParameter("lastname"));
			visitor.setAge(Integer.parseInt(request.getParameter("age")));
			visitor.setAddress(request.getParameter("address"));
			visitor.setPhoneNumber(request.getParameter("phone"));
			visitor.setUsername(request.getParameter("username"));
			visitor.setPassword(request.getParameter("password"));	
			visitor.setAdmin(false);	
			created = visitorService.registerNewVisitor(visitor);

			if(created) {
				request.setAttribute("ok", "User registered successeful.");
				request.getSession().setAttribute("visitor", visitor);
				return "login";

			} else {
				request.setAttribute("error", "User was not registered.");
				return "register";

			}

		} catch (Exception e) {
			System.out.println("ERROR: "+e.getMessage());
			request.setAttribute("error", "Unexpected error.");
			return "registerVisitor";
		}
	}
	
	/**
	 * Update visitor pass controller.
	 *
	 * @return the string
	 */
	@RequestMapping(value = "/updatevisitorpass.htm")
	public String updateVisitorPassController() {
		return "updatePass";
	}
	
	/**
	 * Update pass controller.
	 *
	 * @param request the request
	 * @param response the response
	 * @return the string
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws Exception the exception
	 * @throws ClassNotFoundException the class not found exception
	 */
	@RequestMapping(value = "/updatepass.htm")
	public String updatePassController(HttpServletRequest request, HttpServletResponse response) throws IOException, Exception, ClassNotFoundException {
		VisitorServiceImpl visitorService = new VisitorServiceImpl();
		Visitor visitor = (Visitor)request.getSession().getAttribute("visitor");
		String oldPass = (request.getParameter("Oldpassword"));
		if (oldPass.equals(visitor.getPassword())){
			visitor.setPassword(request.getParameter("password"));
			visitorService.updateVisitorPass(visitor);
			if (visitor.isAdmin())  return "redirect:/eventAdmin.htm";
			else return "redirect:/actArray.htm";
		}
		return "updatePass";
	}
	
}